package com.app.micaihu.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.infor.GetTaskBean;
import com.app.micaihu.bean.news.ShareBean;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UmEventId;
import com.app.micaihu.configure.UserConfigTools;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.custom.view.SlideSelectView;
import com.app.micaihu.custom.view.dialog.ReportDialog;
import com.app.micaihu.listener.HandleListener;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.UserInforManager;
import com.app.utils.biz.Biz;
import com.app.utils.util.HelpUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.image.ImageUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.Utils;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.io.ByteArrayOutputStream;
import java.io.File;

import static android.view.View.GONE;

/**
 * 所有的公用的分享方法
 *
 * @author linkai
 * Created by linkai on 2016/7/28.
 */
public class AppShareUtils implements OnClickListener {

    //弹窗逻辑数据
    public Activity mActivity;
    private AlertDialog dialog;// 默认的分享弹窗
    private ShareBean mShareBean;//分享的数据
    private boolean mIsHideSetLayout;//是否隐藏设置界面
    public String aid = "0";// 转发的文章id
    public String shareType = "0";//转发的类型

    //弹窗控件
    private SlideSelectView slideSelectView;//字体大小滑动
    private TextView mShareCancel;//退出
    private SlideSelectView.onSelectListener mOnSelect;//字体滑动监听
    private View rl_setfontsize, ll_setviewshow;//显示设置窗体
    //	private SeekBar light_seekBar;//亮度调节
    private String newsType;//当前所在页面类型，暂时主要区分举报参数
    private DoMoreClickListener mDoMoreClickListener;
    private HandleListener handleListener;//额外操作监听

    public static String appid = "appid";//微信分享的appid
    public static String appPackName;//app包名
    public static String appShareWay;//分享方式  true代表sdk分享 false代表原生分享


    public AppShareUtils(Activity activity, SlideSelectView.onSelectListener onSelect) {
        this.mActivity = activity;
        this.mOnSelect = onSelect;
    }

    public AppShareUtils(Activity activity) {
        this.mActivity = activity;
        initShareConfig();
    }

    private AppShareUtils() {
        initShareConfig();
    }

    private void initShareConfig() {
        if (TextUtils.equals(appid, "appid")) {
            appid = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.share_appid, "");
            appPackName = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.share_packname, "");
            appShareWay = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.share_way, "0");
        }
    }

    private static AppShareUtils mAppShareUtils;


    public static AppShareUtils getInstance() {
        if (mAppShareUtils == null) {
            mAppShareUtils = new AppShareUtils();
        }
        return mAppShareUtils;
    }


    /**
     * 返回一个分享布局
     *
     * @param activity
     * @return View 分享弹窗布局
     */
    private View getShareDialogView(Activity activity) {
        if (activity == null || activity.isFinishing()) {
            return null;
        }
        // 得到分享布局并且赋予单机事件
        View defaultView = activity.getLayoutInflater().inflate(R.layout.dialog_more_set, null);
        //微信
        View imageView = defaultView.findViewById(R.id.imageView_wechat);
        imageView.setOnClickListener(this);
        //朋友圈
        imageView = defaultView.findViewById(R.id.imageView_wechatmoments);
        imageView.setOnClickListener(this);
        //QQ
        imageView = defaultView.findViewById(R.id.imageView_qq);
        imageView.setOnClickListener(this);
        //QQ空间
        imageView = defaultView.findViewById(R.id.imageView_qzone);
        imageView.setOnClickListener(this);
        //QQ微博
        imageView = defaultView.findViewById(R.id.imageView_weibo);
        imageView.setOnClickListener(this);
        //显示设置
        imageView = defaultView.findViewById(R.id.imageView_font);

        if (mOnSelect == null) {
            imageView.setVisibility(GONE);
        } else {
            imageView.setOnClickListener(this);
        }

        // 复制链接
        imageView = defaultView.findViewById(R.id.imageView_copyurl);
        imageView.setOnClickListener(this);
        // 举报
        imageView = defaultView.findViewById(R.id.imageView_jubao);
        imageView.setOnClickListener(this);
        //夜间模式
        imageView = defaultView.findViewById(R.id.imageView_readmode);
        imageView.setOnClickListener(this);
        Drawable img = mActivity.getResources().getDrawable(R.drawable.share_readnight_btn);
        if (img != null) {
            img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
            ((Button) imageView).setCompoundDrawables(null, img, null, null); //设置左图标
        }
        ((Button) imageView).setText("夜间模式");
        //删除
        imageView = defaultView.findViewById(R.id.imageView_delete);
        imageView.setOnClickListener(this);

        //拉黑
        imageView = defaultView.findViewById(R.id.imageView_defriend);
        imageView.setOnClickListener(this);


        //退出
        mShareCancel = (TextView) defaultView.findViewById(R.id.share_cancel);
        mShareCancel.setOnClickListener(this);

        //初始化显示设置ui
        rl_setfontsize = defaultView.findViewById(R.id.rl_setfontsize);
        ll_setviewshow = defaultView.findViewById(R.id.ll_setviewshow);

//			light_seekBar = (SeekBar) defaultView.findViewById(R.id.light_seekBar);
//			light_seekBar.setOnSeekBarChangeListener(seekBarChange);
//			if(UserConfigTools.screen_brightnes >= 0){
//				light_seekBar.setProgress(UserConfigTools.screen_brightnes);
//			}


        slideSelectView = (SlideSelectView) defaultView.findViewById(R.id.slideSelectView);
        String[] textStrings = new String[]{"小", "中", "大", "特大", "超大"};
        slideSelectView.setString(textStrings);
        slideSelectView.setOnSelectListener(mOnSelect);

        return defaultView;
    }


    /**
     * 展示分享弹窗
     *
     * @param shareBean
     */
    public void showShareDialog(ShareBean shareBean, String newsType) {
        if (this.mActivity != null && !this.mActivity.isFinishing()) {
            this.newsType = newsType;
            this.mShareBean = shareBean;
            if (dialog == null) {
                View view = getShareDialogView(mActivity);
                switch (newsType) {
                    case TypeConstant.ONLY_SHARE:
                        view.findViewById(R.id.imageView_jubao).setVisibility(View.GONE);
                        view.findViewById(R.id.imageView_delete).setVisibility(GONE);
                        view.findViewById(R.id.imageView_defriend).setVisibility(GONE);//拉黑选项
                        view.findViewById(R.id.imageView_copyurl).setVisibility(View.GONE);
                        view.findViewById(R.id.imageView_font).setVisibility(View.GONE);
                        view.findViewById(R.id.imageView_readmode).setVisibility(View.GONE);//夜间模式
                        break;
                    case TypeConstant.PAGE_VIDEO_DETAIL://视频详情
                    case TypeConstant.PAGE_NEWS://新闻
                        view.findViewById(R.id.imageView_delete).setVisibility(GONE);
                        view.findViewById(R.id.imageView_defriend).setVisibility(GONE);//拉黑选项
                        break;
                    case TypeConstant.PAGE_NEWS_DETAIL://正文新闻详情页面
                        view.findViewById(R.id.imageView_jubao).setVisibility(View.GONE);
                        view.findViewById(R.id.imageView_delete).setVisibility(GONE);
                        view.findViewById(R.id.imageView_defriend).setVisibility(GONE);//拉黑选项
                        view.findViewById(R.id.imageView_copyurl).setVisibility(View.VISIBLE);
                        break;
                    case TypeConstant.PAGE_NEWS_DETAIL1://右上角新闻点击
                        view.findViewById(R.id.imageView_delete).setVisibility(GONE);
                        view.findViewById(R.id.imageView_defriend).setVisibility(GONE);//拉黑选项
                        view.findViewById(R.id.imageView_copyurl).setVisibility(View.GONE);
                        view.findViewById(R.id.imageView_readmode).setVisibility(GONE);
                        break;
                    case TypeConstant.PAGE_MINE_POST://自己的帖子
                        view.findViewById(R.id.imageView_jubao).setVisibility(GONE);
                        view.findViewById(R.id.imageView_delete).setVisibility(View.VISIBLE);
                        view.findViewById(R.id.imageView_readmode).setVisibility(GONE);//夜间模式

                        view.findViewById(R.id.imageView_defriend).setVisibility(GONE);//拉黑选项
                        break;
                    case TypeConstant.PAGE_POST://别人的帖子
                        view.findViewById(R.id.imageView_jubao).setVisibility(View.VISIBLE);
                        view.findViewById(R.id.imageView_delete).setVisibility(GONE);
                        view.findViewById(R.id.imageView_readmode).setVisibility(GONE);//夜间模式
                        view.findViewById(R.id.imageView_defriend).setVisibility(GONE);//拉黑选项
                        break;
                    case TypeConstant.PAGE_TOPIC_DETAIL://话题详情
                    case TypeConstant.PAGE_VIDEO_ORIGINAL://原创
                        view.findViewById(R.id.imageView_jubao).setVisibility(GONE);
                        view.findViewById(R.id.imageView_delete).setVisibility(GONE);
                        view.findViewById(R.id.imageView_defriend).setVisibility(GONE);//拉黑选项
                        break;
                    case TypeConstant.PAGE_HOME://我的个人主页
                        view.findViewById(R.id.imageView_jubao).setVisibility(GONE);
                        view.findViewById(R.id.imageView_delete).setVisibility(GONE);
                        view.findViewById(R.id.imageView_defriend).setVisibility(GONE);//拉黑选项

                        break;

                    case TypeConstant.PAGE_OTHER_HOME://别人的主页
                        view.findViewById(R.id.imageView_jubao).setVisibility(View.VISIBLE);
                        view.findViewById(R.id.imageView_delete).setVisibility(GONE);

                        view.findViewById(R.id.imageView_defriend).setVisibility(View.VISIBLE);//拉黑选项
                        break;
                    case TypeConstant.PAGE_AUTHOR_PAGE://作者主页
                        view.findViewById(R.id.imageView_jubao).setVisibility(View.VISIBLE);
                        view.findViewById(R.id.imageView_delete).setVisibility(GONE);

                        view.findViewById(R.id.imageView_defriend).setVisibility(View.GONE);//拉黑选项
                        break;

                    case TypeConstant.PAGE_GAME_DETAIL://游戏详情
                        view.findViewById(R.id.ll_setviewshow).setVisibility(View.GONE);
                        break;
                    default://默认
                        view.findViewById(R.id.imageView_jubao).setVisibility(GONE);
                        view.findViewById(R.id.imageView_delete).setVisibility(GONE);

                        view.findViewById(R.id.imageView_defriend).setVisibility(GONE);//拉黑选项
                        break;
                }

                if (view == null) {
                    ToastUtils.showText("分享数据获取失败,请重试");
                    return;
                }
                dialog = new AlertDialog.Builder(mActivity).create();
                dialog.setCanceledOnTouchOutside(true);
                if (mActivity != null && !mActivity.isFinishing()) {
                    dialog.show();
                    Window window = dialog.getWindow();
                    window.setWindowAnimations(R.style.dialogWindowAnim);
                    window.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                            android.view.WindowManager.LayoutParams.WRAP_CONTENT);
                    window.setBackgroundDrawableResource(android.R.color.transparent); //设置对话框背景为透明
                    window.setGravity(Gravity.BOTTOM);
                    window.setContentView(view);
                }
                try {
                    //设置友盟分享dialog
                    ProgressDialog dialog = new ProgressDialog(mActivity);
                    dialog.setMessage("正在分享");
//                    Config.dialog = dialog;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
            this.dialog.show();
        }

    }


//	/**
//	 * 滑动屏幕亮度的监听
//	 */
//	private SeekBar.OnSeekBarChangeListener seekBarChange = new SeekBar.OnSeekBarChangeListener() {
//
//		int defalutValue;
//
//		@Override
//		public void onStopTrackingTouch(SeekBar seekBar) {
//			//保存亮度
//			UserConfigTools.screen_brightnes = defalutValue;
//			AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.option_Screen_brightnes, defalutValue);
//		}
//
//		@Override
//		public void onStartTrackingTouch(SeekBar seekBar) {
//		}
//
//		@Override
//		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//			defalutValue = progress;
//			BrightnessUtils.setLocalScreenBright(mActivity, progress);
//		}
//	};

    /**
     * 得到分享的页面名称
     *
     * @param newsType
     * @return
     */
    private String getShareTypeName(String newsType) {
        if (TextUtils.isEmpty(newsType)) {
            return "无类型";
        }
        String typename;
        switch (newsType) {

            case TypeConstant.PAGE_NEWS:
                typename = "新闻页面";
                break;
            case TypeConstant.PAGE_COMMENT:
                typename = "评论页面";
                break;
            case TypeConstant.PAGE_MINE_POST:
                typename = "我的帖子页面";
                break;
            case TypeConstant.PAGE_POST:
                typename = "别人的帖子页面";
                break;
            case TypeConstant.PAGE_TOPIC_DETAIL:
                typename = "话题详情页面";
                break;
            case TypeConstant.PAGE_VIDEO_ORIGINAL:
                typename = "原创房间页面";
                break;
            case TypeConstant.PAGE_HOME:
                typename = "个人主页";
                break;
            case TypeConstant.PAGE_OTHER_HOME:

                typename = "别人的主页";
                break;
            case TypeConstant.PAGE_AUTHOR_PAGE:
                typename = "作者主页";
                break;
            case TypeConstant.PAGE_GAME_DETAIL:
                typename = "游戏详情";
            default:
                typename = "无类型";
                break;
        }
        return typename;
    }

    @Override
    public void onClick(View v) {
        if (v == null) {
            return;
        }
        String typename = getShareTypeName(newsType);
        switch (v.getId()) {
            case R.id.imageView_wechat://微信
                StatService.onEvent(mActivity, "031", typename + "弹窗微信分享", 1);// 统计的点击的次数
                MobclickAgentUtils.event(UmEventId.articleshare_click, UmEventId.INSTANCE.getShareWx());
                setWXShareContent(this.mActivity, this.mShareBean, null);
                break;
            case R.id.imageView_wechatmoments://朋友圈
                StatService.onEvent(mActivity, "031", typename + "弹窗朋友圈分享", 1);// 统计的点击的次数
                MobclickAgentUtils.event(UmEventId.articleshare_click, UmEventId.INSTANCE.getShareWechatmoments());
                setWXCShareContent(this.mActivity, this.mShareBean, null);
                break;
            case R.id.imageView_qq://qq
                StatService.onEvent(mActivity, "031", typename + "弹窗qq分享", 1);// 统计的点击的次数
                MobclickAgentUtils.event(UmEventId.articleshare_click, UmEventId.INSTANCE.getShareQQ());
                setQQShareContent(this.mActivity, this.mShareBean, null);
                break;
            case R.id.imageView_qzone://qq空间
                StatService.onEvent(mActivity, "031", typename + "弹窗qq空间分享", 1);// 统计的点击的次数
                MobclickAgentUtils.event(UmEventId.articleshare_click, UmEventId.INSTANCE.getShareQQqzone());
                setQZONEShareContent(this.mActivity, this.mShareBean);
                break;
            case R.id.imageView_weibo://微博
                StatService.onEvent(mActivity, "031", typename + "弹窗微博分享", 1);// 统计的点击的次数
                MobclickAgentUtils.event(UmEventId.articleshare_click, UmEventId.INSTANCE.getShareWeibo());
                setSinaShareContent(this.mActivity, this.mShareBean);
                break;
            case R.id.imageView_font://设置显示
                ll_setviewshow.setVisibility(GONE);
                rl_setfontsize.setVisibility(View.VISIBLE);
                slideSelectView.setCurrentPosition(UserConfigTools.textSize);
                mIsHideSetLayout = true;
                break;
            case R.id.imageView_jubao://举报
                jubao();
                break;

            case R.id.imageView_delete://删除
                if (mDoMoreClickListener != null) {
                    cancleDialog();
                    mDoMoreClickListener.onDeleteClick();
                }
                break;

            case R.id.imageView_copyurl://复制连接
                copy();
                break;
            case R.id.share_cancel://返回
                if (mIsHideSetLayout) {
                    ll_setviewshow.setVisibility(View.VISIBLE);
                    rl_setfontsize.setVisibility(GONE);
                    mIsHideSetLayout = false;
                } else {
                    cancleDialog();
                }

                break;

            case R.id.imageView_defriend://拉黑
                if (mDoMoreClickListener != null) {
                    mDoMoreClickListener.onDefriendClick();
                }
                break;
            case R.id.imageView_readmode://阅读模式
                if (handleListener != null) {
                    handleListener.changeView(null);
                }
                break;
        }
    }


    /**
     * 举报
     */
    private ReportDialog reportDialog;

    private void jubao() {
        if (reportDialog == null) {
            reportDialog = new ReportDialog(mActivity);
        }
        String id = null;
        if (mShareBean != null) {
            id = mShareBean.getArticleId();
        }
        cancleDialog();
//		reportDialog.show(id, true);
        reportDialog.show(id, newsType, getReporttType());
    }


    private String getReporttType() {
        String reportType = "";
        switch (newsType) {
            case TypeConstant.PAGE_NEWS://咨询类型的举报
            case TypeConstant.PAGE_VIDEO_DETAIL:
            case TypeConstant.PAGE_TOPIC_DETAIL:
            case TypeConstant.PAGE_VIDEO_ORIGINAL:
            case TypeConstant.PAGE_NEWS_DETAIL1:

                reportType = TypeConstant.JUBAO_NEWS;
                break;
            case TypeConstant.PAGE_OTHER_HOME://个人主页的举报
            case TypeConstant.PAGE_AUTHOR_PAGE:
                reportType = TypeConstant.JUBAO_USER;
                break;
            case TypeConstant.PAGE_COMMENT://一级评论
                reportType = TypeConstant.JUBAO_COMMENT_PARENT;
                break;
            case TypeConstant.PAGE_COMMENT_CHILD://非一级评论
                reportType = TypeConstant.JUBAO_COMMENT_CHILD;
                break;
            case TypeConstant.PAGE_POST://一级帖子
                reportType = TypeConstant.JUBAO_POST;
                break;
            case TypeConstant.PAGE_POST_COMMENT_CHILD://非一级的贴子评论
                reportType = TypeConstant.JUBAO_POST_CHILD;
                break;
        }

        return reportType;

    }


    /**
     * 复制
     */
    private void copy() {
        if (mShareBean == null) {
            ToastUtils.makeText(R.drawable.handle_success, "复制失败");
            return;
        }
        HelpUtils.copy(mShareBean.getShareUrl(), AppApplication.getInstance());
        cancleDialog();
        ToastUtils.makeText(R.drawable.handle_success, "已复制");
    }

    /**
     * 隐藏dialog
     */
    public void cancleDialog() {
        try {
            if (this.dialog != null && this.dialog.isShowing()) {
                this.dialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /******************* 第三方分享调用方法 start *******************/
//    /**
//     * 调用友盟自带的分享弹窗
//     *
//     * @param activity
//     * @param shareBean
//     */
//    public void UMShareView(Activity activity, ShareBean shareBean) {
//        if (shareBean == null) {
//            shareBean = new ShareBean();
//        }
//        aid = shareBean.getArticleId();
//        UMImage urlImage = new UMImage(activity, shareBean.getShareImg());
//        new ShareAction(activity).setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
//                .withTitle(shareBean.getShareTitle(null))
//                .withText(shareBean.getShareSummary())
//                .withMedia(urlImage)
//                .setCallback(umShareListener)
//                .open();
//    }

    /**
     * 设置微信朋友圈分享的内容
     *
     * @param activity
     * @param newsContent
     */
    public void setWXCShareContent(final Activity activity, ShareBean newsContent, UMShareListener shareListener) {
        if (newsContent == null) {
            newsContent = new ShareBean();
        }
        aid = newsContent.getArticleId();
        shareType = newsContent.getShareType();
        if (TextUtils.equals("2", appShareWay)) {
            UMWeb urlImage = new UMWeb(newsContent.getShareWxurl());
            urlImage.setTitle(newsContent.getShareTitle(null));
            urlImage.setDescription(newsContent.getShareSummary());
            urlImage.setThumb(new UMImage(Utils.getApp(), newsContent.getShareImg()));
            new ShareAction(activity).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(shareListener == null ? umShareListener : shareListener)
                    .withMedia(urlImage)
                    .share();
            cancleDialog();

            return;
        }


        if (TextUtils.equals("0", appShareWay)) {
            //sdk分享
            final IWXAPI api = WXAPIFactory.createWXAPI(new HackerApp(mActivity, appPackName), appid);
            WXWebpageObject webpage = new WXWebpageObject();
            webpage.webpageUrl = newsContent.getShareWxurl();
            final WXMediaMessage msg = new WXMediaMessage(webpage);
            msg.title = newsContent.getShareTitle(null);
            msg.description = newsContent.getShareSummary();
            String name = newsContent.getShareImg().substring(newsContent.getShareImg().lastIndexOf("/") + 1) + ".jpg";
            OkHttp3Helper.getInstance().downAsynFile_Cache(newsContent.getShareImg(),
                    AppConfigTools.USERSAVEIMG, name, new OkHttp3Helper.OnDownLoadResponCallBack() {

                        @Override
                        public void onStart() {
                            DialogUtils.getInstance().showProgressDialog(activity, "正在分享...");
                        }

                        @Override
                        public void onSucess(File file) {
                            DialogUtils.getInstance().dismissProgressDialog();
                            if (file != null) {
                                Bitmap thumbBmp = ImageUtils.zoomImage(file, 100, 100);
                                msg.thumbData = bmpToByteArray(thumbBmp, true);
                                SendMessageToWX.Req req = new SendMessageToWX.Req();
                                req.transaction = buildTransaction("webpage");
                                req.message = msg;
                                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                                api.sendReq(req);
                                cancleDialog();
                            }
                        }

                        @Override
                        public void onFailure() {
                            DialogUtils.getInstance().dismissProgressDialog();
                            Bitmap bitmap = BitmapFactory.decodeResource(AppApplication.getInstance().getResources(), R.mipmap.icon);
                            Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 150, 150, true);
                            bitmap.recycle();
                            msg.thumbData = bmpToByteArray(thumbBmp, true);
                            SendMessageToWX.Req req = new SendMessageToWX.Req();
                            req.transaction = buildTransaction("webpage");
                            req.message = msg;
                            req.scene = SendMessageToWX.Req.WXSceneTimeline;
                            api.sendReq(req);
                            cancleDialog();
                        }
                    });
        } else {
            //原生分享
            new AndroidNativeShareUtils(activity).shareWeChatFriendCircleTodownload(newsContent.getShareTitle(),
                    newsContent.getShareTitle() + "\n" + newsContent.getShareWxurl(), newsContent.getShareImg(), "");
            cancleDialog();
        }
        if (!TextUtils.isEmpty(aid)) {
            ParamMap mapParms = new ParamMap();
            if (!StringUtils.isEmpty(Biz.getInstance().uid())) {
                mapParms.putEncode("uid", Biz.getInstance().uid());
            } else {
                mapParms.putEncode("uid", "0");
            }
            mapParms.putEncode("shareType", "3");
            if (TextUtils.isEmpty(shareType)) {
                shareType = TypeConstant.SHARE_TYPE_NEWS;
            }
            mapParms.putEncode("operatorType", shareType);
            mapParms.putEncode("articleId", aid);
            HttpUtils.ParmsMapMD5(mapParms);
            HttpListener<DataBean<GetTaskBean>> httpListener = new HttpListener<DataBean<GetTaskBean>>() {
                @Override
                public void onError(VolleyError error) {
                }

                @Override
                public void onSuccess(DataBean<GetTaskBean> response) {

                    if (response.noError() && response.getData() != null
                            && response.getData().getIsGetTask("分享文章")) {
                        //刷新任务
                        UserInforManager.getInstance().getUserTask(mActivity, false);
                    }

                }
            };

            //请求网络
            HttpUtils.addPostRequest(URIContant.NEWS_SHARE_COUNT, new TypeToken<DataBean<GetTaskBean>>() {
            }.getType(), null, mapParms, httpListener);
        }
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    /**
     * 设置微信分享的内容
     *
     * @param activity
     * @param newsContent
     */
    public void setWXShareContent(final Activity activity, ShareBean newsContent, UMShareListener shareListener) {
        if (newsContent == null) {
            newsContent = new ShareBean();
        }
        aid = newsContent.getArticleId();
        shareType = newsContent.getShareType();
        if (TextUtils.equals("2", appShareWay)) {
            UMWeb urlImage = new UMWeb(newsContent.getShareWxurl());
            urlImage.setDescription(newsContent.getShareSummary());
            urlImage.setTitle(newsContent.getShareTitle(null));
            urlImage.setThumb(new UMImage(Utils.getApp(), newsContent.getShareImg()));
            new ShareAction(activity).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(shareListener == null ? umShareListener : shareListener)
                    .withMedia(urlImage)
                    .share();
            cancleDialog();
            return;
        }


        if (TextUtils.equals("0", appShareWay)) {
            final IWXAPI api = WXAPIFactory.createWXAPI(new HackerApp(activity, appPackName), appid);
            WXWebpageObject webpage = new WXWebpageObject();
            webpage.webpageUrl = newsContent.getShareWxurl();
            final WXMediaMessage msg = new WXMediaMessage(webpage);
            msg.title = newsContent.getShareTitle(null);
            msg.description = newsContent.getShareSummary();
            String name = newsContent.getShareImg().substring(newsContent.getShareImg().lastIndexOf("/") + 1) + ".jpg";
            OkHttp3Helper.getInstance().downAsynFile_Cache(newsContent.getShareImg(),
                    AppConfigTools.USERSAVEIMG, name, new OkHttp3Helper.OnDownLoadResponCallBack() {

                        @Override
                        public void onStart() {
                            DialogUtils.getInstance().showProgressDialog(activity, "正在分享...");
                        }

                        @Override
                        public void onSucess(File file) {
                            DialogUtils.getInstance().dismissProgressDialog();
                            if (file != null) {
                                Bitmap thumbBmp = ImageUtils.zoomImage(file, 100, 100);
                                msg.thumbData = bmpToByteArray(thumbBmp, true);
                                SendMessageToWX.Req req = new SendMessageToWX.Req();
                                req.transaction = buildTransaction("webpage");
                                req.message = msg;
                                req.scene = SendMessageToWX.Req.WXSceneSession;
                                api.sendReq(req);
                                cancleDialog();
                            }
                        }

                        @Override
                        public void onFailure() {
                            DialogUtils.getInstance().dismissProgressDialog();
                            Bitmap bitmap = BitmapFactory.decodeResource(AppApplication.getInstance().getResources(), R.mipmap.icon);
                            Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 150, 150, true);
                            bitmap.recycle();
                            msg.thumbData = bmpToByteArray(thumbBmp, true);
                            SendMessageToWX.Req req = new SendMessageToWX.Req();
                            req.transaction = buildTransaction("webpage");
                            req.message = msg;
                            req.scene = SendMessageToWX.Req.WXSceneSession;
                            api.sendReq(req);
                            cancleDialog();
                        }
                    });

        } else {
            //原生分享
            new AndroidNativeShareUtils(activity).shareWeChatFriend(newsContent.getShareTitle(),
                    newsContent.getShareTitle() + "\n" + newsContent.getShareWxurl(), "", "");
            cancleDialog();
        }
        if (!TextUtils.isEmpty(aid)) {
            ParamMap mapParms = new ParamMap();
            if (!StringUtils.isEmpty(Biz.getInstance().uid())) {
                mapParms.putEncode("uid", Biz.getInstance().uid());
            } else {
                mapParms.putEncode("uid", "0");
            }
            mapParms.putEncode("shareType", "2");
            if (TextUtils.isEmpty(shareType)) {
                shareType = TypeConstant.SHARE_TYPE_NEWS;
            }
            mapParms.putEncode("operatorType", shareType);
            mapParms.putEncode("articleId", aid);
            HttpUtils.ParmsMapMD5(mapParms);
            HttpListener<DataBean<GetTaskBean>> httpListener = new HttpListener<DataBean<GetTaskBean>>() {
                @Override
                public void onError(VolleyError error) {
                }

                @Override
                public void onSuccess(DataBean<GetTaskBean> response) {

                    if (response.noError() && response.getData() != null
                            && response.getData().getIsGetTask("分享文章")) {
                        //刷新任务
                        UserInforManager.getInstance().getUserTask(mActivity, false);
                    }

                }
            };

            //请求网络
            HttpUtils.addPostRequest(URIContant.NEWS_SHARE_COUNT, new TypeToken<DataBean<GetTaskBean>>() {
            }.getType(), null, mapParms, httpListener);
        }

    }

    //设置QQ分享的内容
    public void setQQShareContent(Activity activity, ShareBean newsContent, UMShareListener shareListener) {
        if (newsContent == null) {
            newsContent = new ShareBean();
        }
        aid = newsContent.getArticleId();
        shareType = newsContent.getShareType();
        UMWeb urlImage = new UMWeb(newsContent.getShareUrl());
        urlImage.setTitle(newsContent.getShareTitle(null));
        urlImage.setDescription(newsContent.getShareSummary());
        urlImage.setThumb(new UMImage(Utils.getApp(), newsContent.getShareImg()));
        new ShareAction(activity).setPlatform(SHARE_MEDIA.QQ).setCallback(shareListener == null ? umShareListener : shareListener)
                .withMedia(urlImage)
                .share();
        cancleDialog();
    }


    //设置QQ空间分享的内容
    public void setQZONEShareContent(Activity activity, ShareBean newsContent) {
        if (newsContent == null) {
            newsContent = new ShareBean();
        }
        aid = newsContent.getArticleId();
        shareType = newsContent.getShareType();
        UMWeb urlImage = new UMWeb(newsContent.getShareUrl());
        urlImage.setTitle(newsContent.getShareTitle(null));
        urlImage.setDescription(newsContent.getShareSummary());
        urlImage.setThumb(new UMImage(Utils.getApp(), newsContent.getShareImg()));
        new ShareAction(activity).setPlatform(SHARE_MEDIA.QZONE).setCallback(umShareListener)
                .withMedia(urlImage)
                .share();
        cancleDialog();
    }

    //设置微博分享的内容
    public void setSinaShareContent(Activity activity, ShareBean newsContent) {
        if (newsContent == null) {
            newsContent = new ShareBean();
        }
        aid = newsContent.getArticleId();
        shareType = newsContent.getShareType();
        UMWeb urlImage = new UMWeb(newsContent.getShareUrl());
        urlImage.setTitle(newsContent.getShareTitle(null));
        urlImage.setDescription(newsContent.getShareSummary() + " @迷彩虎 ");
        urlImage.setThumb(new UMImage(Utils.getApp(), newsContent.getShareImg()));
        new ShareAction(activity).setPlatform(SHARE_MEDIA.SINA).setCallback(umShareListener)
                .withMedia(urlImage)
                .share();
        cancleDialog();
    }


    //分享回调监听
    public UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            //统计分享的文章
            writeShareCount(platform);
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtils.makeText(R.drawable.handle_fail, "分享失败");
            String typename;
            if (platform != null) {
                if (SHARE_MEDIA.SINA.equals(platform.toSnsPlatform().mPlatform)) {
                    typename = "新浪微博";
                } else if (SHARE_MEDIA.WEIXIN.equals(platform.toSnsPlatform().mPlatform)) {
                    typename = "微信";
                } else if (SHARE_MEDIA.WEIXIN_CIRCLE.equals(platform.toSnsPlatform().mPlatform)) {
                    typename = "朋友圈";
                } else if (SHARE_MEDIA.QQ.equals(platform.toSnsPlatform().mPlatform)) {
                    typename = "qq";
                } else if (SHARE_MEDIA.QZONE.equals(platform.toSnsPlatform().mPlatform)) {
                    typename = "qq空间";
                } else {
                    typename = "无类型";
                }
            } else {
                typename = "没有获取到类型";
            }
            StatService.onEvent(mActivity, "035", getShareTypeName(newsType) + typename + "分享失败", 1);// 统计的点击
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtils.makeText("分享取消");
        }


    };

    /**
     * 返回分享dialog
     *
     * @return
     */
    public Dialog getShareDialog() {
        return dialog;
    }


    /**
     * 统计分享的文章
     */
    public void writeShareCount(SHARE_MEDIA platform) {

        ParamMap mapParms = new ParamMap();
        String type = "0";
        String typename;
        if (platform != null) {
            if (SHARE_MEDIA.SINA.equals(platform.toSnsPlatform().mPlatform)) {
                type = "1";
                typename = "新浪微博";
            } else if (SHARE_MEDIA.WEIXIN.equals(platform.toSnsPlatform().mPlatform)) {
                type = "2";
                typename = "微信";
            } else if (SHARE_MEDIA.WEIXIN_CIRCLE.equals(platform.toSnsPlatform().mPlatform)) {
                type = "3";
                typename = "朋友圈";
            } else if (SHARE_MEDIA.QQ.equals(platform.toSnsPlatform().mPlatform)) {
                type = "4";
                typename = "qq";
            } else if (SHARE_MEDIA.QZONE.equals(platform.toSnsPlatform().mPlatform)) {
                type = "5";
                typename = "qq空间";
            } else {
                type = "0";
                typename = "无类型";
            }
        } else {
            typename = "没有获取到类型";
        }
        if (UserInforManager.getInstance().isLogin()) {
            mapParms.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
        } else {
            mapParms.putEncode("uid", "0");
        }
        mapParms.putEncode("shareType", type);
        if (TextUtils.isEmpty(shareType)) {
            shareType = TypeConstant.SHARE_TYPE_NEWS;
        }
        mapParms.putEncode("operatorType", shareType);
        mapParms.putEncode("articleId", aid);
        HttpUtils.ParmsMapMD5(mapParms);
        HttpListener<DataBean<GetTaskBean>> httpListener = new HttpListener<DataBean<GetTaskBean>>() {
            @Override
            public void onError(VolleyError error) {
                ToastUtils.makeText(R.drawable.handle_success, "分享成功");
            }

            @Override
            public void onSuccess(DataBean<GetTaskBean> response) {

                if (response.noError() && response.getData() != null
                        && response.getData().getIsGetTask("分享文章")) {
                    //刷新任务
                    UserInforManager.getInstance().getUserTask(mActivity, false);
                } else {
                    ToastUtils.makeText(R.drawable.handle_success, "分享成功");
                }

            }
        };

        //请求网络
        HttpUtils.addPostRequest(URIContant.NEWS_SHARE_COUNT, new TypeToken<DataBean<GetTaskBean>>() {
        }.getType(), null, mapParms, httpListener);

        StatService.onEvent(mActivity, "034", getShareTypeName(newsType) + typename + "分享成功", 1);// 统计的点击

    }

    /******************* 第三方分享调用方法 end *******************/


    public interface DoMoreClickListener {
        void onDeleteClick();

        void onDefriendClick();

    }

    public void setOnDoMoreClickListener(DoMoreClickListener mDoMoreClickListener) {
        this.mDoMoreClickListener = mDoMoreClickListener;
    }

    public void setHandleListener(HandleListener handleListener) {
        this.handleListener = handleListener;
    }
}
